<template>
  <div>
    <div>
      <div class="top">
        <el-button @click="save" type="primary">导出表格</el-button>
        <el-button @click="showFn('添加商品')" type="primary"
          >添加商品</el-button
        >
        <el-input
          placeholder="请搜索商品名"
          v-model.trim="val"
          debounce
          @change="searchFn(val)"
        >
          <template #append>
            <el-button
              icon="el-icon-search"
              el-icon--large
              el-icon--left
              @click="searchFn(val)"
            />
          </template>
        </el-input>
      </div>

      <el-dialog
        :title="title"
        :visible.sync="centerDialogVisible"
        width="50%"
        center
        show-close
        modal
      >
        <span class="tit">商品详细信息</span>
        <div class="picture">
          <span class="wenzi">上传图片</span>
          <el-upload
            class="avatar-uploader"
            action="http://182.92.162.156:8083/product//uppro"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
        <div class="name">
          <span class="wenzi">商品名称</span>
          <el-input v-model.trim="formData.name" type="text"></el-input>
        </div>
        <div class="type">
          <span class="wenzi">适用对象</span>
          <el-select v-model="formData.type" name="formData.type">
            <el-option value="">请选择</el-option>
            <el-option value="主粮">主粮</el-option>
            <el-option value="日用">日用</el-option>
            <el-option value="服务">服务</el-option>
            <el-option value="牵引绳">牵引绳</el-option>
            <el-option value="玩具">玩具</el-option>
            <el-option value="罐头">罐头</el-option>
            <el-option value="衣服">衣服</el-option>
            <el-option value="零食">零食</el-option>
          </el-select>
        </div>
        <div class="status">
          <span class="wenzi">商品状态</span>
          <el-select v-model="formData.status" name="formData.status">
            <el-option value="">请选择</el-option>
            <el-option value="0">上架</el-option>
            <el-option value="1">下架</el-option>
          </el-select>
        </div>
        <div class="desc">
          <span class="wenzi">商品描述</span
          ><el-input type="textarea" v-model.trim="formData.desc"></el-input>
        </div>
        <div class="price">
          <span class="wenzi">商品价格</span
          ><el-input type="text" v-model.trim="formData.price"></el-input>
        </div>
        <div class="inventory">
          <span class="wenzi">商品库存</span
          ><el-input type="text" v-model.trim="formData.inventory"></el-input>
        </div>

        <span slot="footer" class="dialog-footer" v-if="title == '添加商品'">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </span>
        <span slot="footer" class="dialog-footer" v-else>
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="edit(id, formData)"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>

    <div class="product">
      <el-table :data="list" style="width: 100%" height="450" stripe>
        <el-table-column prop="id" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column
          prop="proname"
          label="产品名称"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="type" label="类型" align="center">
        </el-table-column>
        <el-table-column prop="proinfo" label="描述" align="center">
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
        </el-table-column>
        <el-table-column prop="price" label="价格" align="center">
        </el-table-column>
        <el-table-column prop="inventory" label="库存" align="center">
        </el-table-column>
        <el-table-column prop="actions" label="actions" align="center">
          <template slot-scope="scope">
            <div class="actions">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showFn1('编辑商品', scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="delete1(scope.row.id)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total.length"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible2"
      width="30%"
      center
    >
      <span>确定要删除这条商品数据么</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delete2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { saveExcel } from "@/utils/toExl";
import Vue from "vue";
import { Product } from "@/api";
import { Message } from "element-ui";
// Vue.use(Message)
Vue.prototype.$message = Message;
// import axios from 'axios'
export default {
  data() {
    return {
      imageUrl: null,
      total: "",
      limit: 10,
      currentPage: 1,
      id: "",
      title: "",
      list: [],
      val: "",
      hidden: false,
      centerDialogVisible: "",
      centerDialogVisible2: false,
      formData: {
        // id:'',
        name: "",
        type: "",
        desc: "",
        status: "",
        price: "",
        inventory: "",
        imgUrl:""
      },
      centerDialogVisible: false,
    };
  },
  created() {
    //分页取
    this.currentPage = Number(localStorage.getItem("lastPage")) || 1;
    this.page();
    console.log(this.currentPage, "get");
  },
  methods: {
    // async categoryList(){//分类
    //   let res  = Product["categorylist"]()
    //   console.log(res,"商品分类");
    // },
    save() {
      var option = {};
      option.fileName = "商品excel";
      option.datas = [
        {
          //第一个sheet
          sheetData: this.total.map((item, index) => {
            item.order = index + 1;
            return item;
          }),
          sheetName: "商品表",
          sheetFilter: [
            "order",
            "proname",
            "type",
            "proinfo",
            "status",
            "price",
            "inventory",
          ],
          sheetHeader: [
            "序号",
            "产品名称",
            "类型",
            "描述",
            "状态",
            "价格",
            "库存",
          ],
        },
      ];
      saveExcel(option);
    },
    async edit(id, formData) {
      console.log(id, "gengxin");
      let res = Product["update"](id, formData);
      console.log(res, "更新");
      this.centerDialogVisible = false;
      this.getList();
      this.page();
      this.$message({
        message: this.title === "编辑商品" ? "成功修改商品信息" : "",
        type: "success",
      });
    },
    handleSizeChange(val) {
      //分页
      this.limit = val;
      this.currentPage = 1;
      this.page();
      // console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      //分页存
      this.currentPage = val;
      this.page();
      localStorage.setItem("lastPage", this.currentPage);
      // console.log(`当前页: ${val}`);
    },
    async page() {
      let res = await Product["page"](this.currentPage, this.limit);
      console.log(res, "分页信息");
      this.list = res.data;
    },
    showFn(til) {
      this.title = til;
      this.centerDialogVisible = true;
      if( this.centerDialogVisible){
        for (let key in this.formData) {
            this.formData[key] = ''; // 给属性赋空字符串的值
                    }
                    this.imageUrl = ''
      }
    },
    showFn1(til, row) {
      this.title = til;
      this.id = row.id;
      this.formData.name = row.proname;
      this.formData.type = row.type;
      this.formData.desc = row.proinfo;
      this.formData.status = row.status;
      this.formData.price = row.price;
      this.formData.imgUrl = row.img;
      this.formData.inventory = row.inventory;
      
      this.centerDialogVisible = true;
      this.getList();
      this.xxx()
      // this.page()
    },
    async addList(obj) {
      let res = await Product["add"](obj);
      console.log(res, "添加商品");
    },
    add() {
      // const time = new Date();
      // // 将时间赋值给表单数据中的id字段
      // this.formData.id = time;
      let value = Object.values(this.formData);
      let isTrue = value.every((item) => item !== "");
      console.log(this.formData, "formData");
      // console.log(this.formData.id);
      if (isTrue) {
        this.addList(this.formData);
        this.$message({
          message:
            this.title === "添加商品" ? "成功添加一件商品" : "成功修改商品信息",
          type: "success",
        });
        this.formData = {};
        this.centerDialogVisible = false;
        this.getList();
      } else {
        this.$message({
          message: "表单内容全部为必填项，不能为空",
          type: "error",
        });
      }
    },
    xxx(){
      console.log(this.formData.imgUrl,"this.formData.imgUrl")
      this.imageUrl ='http://182.92.162.156:8083/product/downpropic?filename=' + this.formData.imgUrl
    },
    handleAvatarSuccess(res, file) { //选择图片成功时的数据
            // User['downattr']($store.state.user.user.attr)
            console.log(res + '后端返回的图片名字')
            this.formData.imgUrl = res;
           
            this.imageUrl = URL.createObjectURL(file.raw);
           
        },
    beforeAvatarUpload(file) { //上传图片
            const isJPG = file.type === 'image/jpeg' || 'image/webp' || 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG,webp,png 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
    async searchFn(name) {
      if (name) {
        let res = await Product["find"](name);
        console.log(res, "查找商品");
        this.list = res.data;
      } else {
        this.page();
        this.getList();
      }
    },
    async getList() {
      let res = await Product["list"]();
      this.total = res.data;
      console.log(res, "商品列表");
      // console.log(this.list,"list");
    },
    async delete1(id) {
      this.id = id;
      this.centerDialogVisible2 = true;
    },
    async delete2() {
      let id = this.id;
      console.log(id, "删除id");
      let res = await Product["del"](id);
      this.centerDialogVisible2 = false;
      console.log(res, "删除商品");
      this.getList();
    },
  },
  mounted() {
    // this.categoryList();
    this.getList();
    this.page();
  },
};
</script>

<style scoped>
.el-button {
  margin-left: 10px;
}
.message {
  font-size: 20px;
  color: red;
}
.tit {
  font-size: 24px;
}
.wenzi {
  display: inline-block;
  padding: 10px;
  width: 76px;
  height: 41px;
}
.top {
  display: flex;
}
.el-input {
  width: calc(100% - 90px);
  margin-left: 10px;
}
.el-button--default {
  margin-left: -14px;
}
.actions {
  display: flex;
  justify-content: space-between;
}
.name,
.type,
.desc,
.status,
.price,
.inventory {
  padding: 5px 0;
}
.desc {
  display: flex;
}
.el-select {
  width: 543px;
  margin-left: 10px;
}
.type {
  display: flex;
}
.el-textarea {
  width: 543px;
  margin-left: 10px;
}
.block {
  display: flex;
  justify-content: center;
  padding: 30px;
}
.picture{
  display: flex;
}
.avatar-uploader{
  border: 1px solid #e1e1e1;
  margin-left: 10px;
  width: 50px;
  height: 50px;
}
.avatar-uploader-icon::before{
  content: ""\e6d9"";
  width: 10px;
  height: 10px;
  font-size: 40px;
  margin-right: 2px; /* 示例样式，根据需求修改 */
  position: relative;
  top: 5px;
  left:5px;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar {
  width: 50px;
  height: 50px;
  display: block;
}
</style>